﻿using Anke.SHManage.BLL;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Anke.SHManage.Model;
using Anke.SHManage.BLL.MobileBLL;
using Anke.SHManage.Model.MobileModel;
using System.Web.Script.Serialization;
using System.Configuration;
using System.IO;
using System.Text;
using System.Net;
using Anke.SHManage.Model.PatientModel;
using Anke.SHManage.Model.ExtentionModel;
using System.Security.Cryptography;

namespace Anke.SHManage.Web.Areas.BM.Controllers
{
    [SkipLoginAttribute]
    public class MobileTaskController : Controller
    {
        private static object m_SyncRoot = new Object();//互斥对象
        private JavaScriptSerializer js = new JavaScriptSerializer();
        private string YinLianUrl = ConfigurationManager.AppSettings["YinLianUrl"].ToString();//20200813 sr

        [HttpPost]
        public ActionResult Index()
        {
            string userCode = Request.Form["userCode"].ToString();

            string taskCode = Request.Form["TaskCode"].ToString();

            string errorMsg = "成功";

            //2015-12-04 这个实体修改了
           var list = new MobileTaskBLL().GetMobileTaskListBy(userCode, taskCode, ref errorMsg);

            if (list != null)
                return Json(new { success = true, errorMsg = errorMsg, list = list }, "appliction/json", JsonRequestBehavior.AllowGet);
            else
                return Json(new { success = false, errorMsg = errorMsg, list = "" }, "appliction/json", JsonRequestBehavior.AllowGet);
        }

        #region 根据时间、流水号、分中心编码获取出车信息
        /// <summary>
        /// 根据时间、流水号、分中心编码获取出车信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Gettask()
        {
            string begintime = Request.Form["begintime"].ToString();
            string endtime = Request.Form["endtime"].ToString();
            string centerCode = Request.Form["centerCode"].ToString();
            string taskOrder = Request.Form["taskOrder"].ToString();

            string errorMsg = "成功";

            var list = new MobileTaskBLL().GetMobileTaskListsBy(begintime, endtime, centerCode, taskOrder, ref errorMsg);

            if (list.Count > 0)
                return Json(new { success = true, errorMsg = errorMsg, list = list }, "appliction/json", JsonRequestBehavior.AllowGet);
            else
                return Json(new { success = false, errorMsg = errorMsg, list = "" }, "appliction/json", JsonRequestBehavior.AllowGet);
        }
        #endregion


        #region 根据任务编码和病历序号查询病历
        /// <summary>
        /// 根据任务编码和病历序号查询病历
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetPatientRecordInfo()
        {
            string TaskCode = Request.Form["TaskCode"].ToString();
            int PatientOrder = Convert.ToInt32(Request.Form["PatientOrder"]);
            int ChargeType = 0;
            ChargeType = new MobilePatientRecordBLL().GetIFChargeByTaskCode(TaskCode, PatientOrder);
            M_PatientRecord pr = null;
            M_PatientRecordAppend pra = null;
            M_PatientRecordCPR prc = null;

            List<M_PatientRecordRescue> prrs = null;//救治记录
            List<M_PatientRecordMeasure> prms = null;//措施表
            List<M_PatientRecordDrug> prds = null;//药品表
            List<M_PatientRecordSanitation> prss = null;//耗材表 
            //下面方法需要修改 2015-12-04
            new MobilePatientRecordBLL().GetPatientAndRescueInfo(TaskCode, PatientOrder, out pr, out pra, out prc, out prrs, out prms, out prds, out prss);
            if (pr != null)
                return Json(new { success = true, pr = pr, pra = pra, prc = prc, prrs = prrs, prms = prms, prds = prds, prss = prss, ChargeType }, "appliction/json", JsonRequestBehavior.AllowGet);
            else
            {
                M_AttemperData result = new M_PatientRecordBLL().GetAttemperData(TaskCode, "");//根据任务编码获取调度信息
                pr = new M_PatientRecord();
                pr.CallOrder = result.CallOrder;
                pr.PatientOrder = 1;
                pr.LocalAddress = result.LocalAddress;
                pr.Name = result.Name;
                pr.Sex = result.Sex;
                pr.Age = result.Age;
                pr.AgeType = result.AgeType;
                pr.Station = result.Station;
                pr.OutStationCode = result.StationCode;
                pr.DrivingTime = result.DrivingTime;//出车时间
                pr.ArriveSceneTime = result.ArriveSceneTime;//到达现场时刻
                pr.LeaveSceneTime = result.LeaveSceneTime;//离开现场时刻
                pr.ArriveDestinationTime = result.ArriveDestinationTime;//到达医院时刻
                pr.SendAddress = result.SendAddress;
                pr.Driver = result.Driver;
                pr.DoctorAndNurse = result.Doctor + result.Nurse;
                pr.StretcherBearersI = result.StretcherBearers;
                pr.ContactTelephone = result.ContactTelephone;
                pr.ForHelpTelephone = result.ForHelpPhone;//20151211呼救电话
                pr.ForArea = result.Area;//20151211区域
                pr.OriginalTaskType = result.AlarmType;//20151211原事件类型
                return Json(new { success = true, pr = pr, pra = pra, prc = prc, prrs = prrs, prms = prms, prds = prds, prss = prss, ChargeType }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region 验证PAD配置参数密码是否正确
        /// <summary>
        /// 验证PAD配置参数密码是否正确
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult VerificationPassWord()
        {
            string pw = Request.Form["passWord"].ToString();

            if (AppConfig.GetConfigString("PADPassWord") == pw)
            {
                //验证成功
                return Json(new { msg = true }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { msg = false }, "appliction/json", JsonRequestBehavior.AllowGet);

        }
        #endregion

        #region 提交病历
        /// <summary>
        /// 提交病历
        /// </summary>
        /// <returns></returns>
        public ActionResult SubmitPatientRecord()
        {
            try
            {
                string TaskCode = Request.Form["TaskCode"].ToString();
                int PatientOrder = Convert.ToInt32(Request.Form["PatientOrder"]);
                string EvenType = Request.Form["EvenType"].ToString();
                string TaskOrder = Request.Form["TaskOrder"].ToString();
                string DispatcherInfo = Request.Form["DispatcherInfo"].ToString();
                string TiJianInfo = Request.Form["TiJianInfo"].ToString();
                string CPRInfo = Request.Form["CPRInfo"].ToString();
                string RecordRescue = Request.Form["RecordRescue"].ToString();
                string RecordSanitation = Request.Form["RecordSanitation"].ToString();
                string RecordMeasure = Request.Form["RecordMeasure"].ToString();
                string RecordDrug = Request.Form["RecordDrug"].ToString();
                string WorkCode = Request.Form["WorkCode"].ToString();
                string PersonName = Request.Form["PersonName"].ToString();
                M_PatientRecord pr = JsonHelper.GetJsonInfoBy<M_PatientRecord>(DispatcherInfo);
                M_PatientRecordAppend pra = JsonHelper.GetJsonInfoBy<M_PatientRecordAppend>(TiJianInfo);
                M_PatientRecordCPR prc = JsonHelper.GetJsonInfoBy<M_PatientRecordCPR>(CPRInfo);

                List<M_PatientRecordDiag> prDiag = null;//初步诊断
                List<M_PatientRecordECGImpressions> prECG = null;//心电图印象

                List<M_PatientRecordRescue> prrs = JsonHelper.GetJsonInfoBy<List<M_PatientRecordRescue>>(RecordRescue);//救治记录
                List<M_PatientRecordMeasure> prms = JsonHelper.GetJsonInfoBy<List<M_PatientRecordMeasure>>(RecordMeasure);//措施表
                List<M_PatientRecordDrug> prds = JsonHelper.GetJsonInfoBy<List<M_PatientRecordDrug>>(RecordDrug);//药品表
                List<M_PatientRecordSanitation> prss = JsonHelper.GetJsonInfoBy<List<M_PatientRecordSanitation>>(RecordSanitation);//耗材表

                List<M_PatientRecordLossDrug> prLossDrug = null;//损耗药品子表
                List<M_PatientRecordLossSanitation> prLossSanitation = null;//损耗耗材子表

                string errorMsg = "";
                //下面方法需要修改 2015-12-04
                if (new MobilePatientRecordBLL().PADAddPatientRecord(TaskCode, PatientOrder, EvenType, TaskOrder, pr, pra, prc, prDiag
                                     , prECG, prrs, prms, prds, prss, prLossDrug, prLossSanitation, WorkCode, PersonName, ref errorMsg))
                {
                    SavePatientRecordMaterialUse(prds, prss, prms, TaskCode, PatientOrder); //add2021-10-18 plq 医保上线移植
                    //add2022-08-17 plq  新增 诊疗操作字段，更新诊疗操作--移植自闵行
                    M_PatientRecordBLL bll = new M_PatientRecordBLL();
                    bll.UpdateMeasureInformation(TaskCode, PatientOrder); 
                    return Json(new { success = true, msg = TaskOrder }, "appliction/json", JsonRequestBehavior.AllowGet);
                }
                else
                {
                    LogUtility.Error("MobileTask/SubmitPatientRecord", "上传病历失败！原因：" + errorMsg);
                    return Json(new { success = false, msg = "上传病历失败！原因：" + errorMsg }, "appliction/json", JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("MobileTask/SubmitPatientRecord", ex.Message);
                return Json(new { success = false, msg = "上传病历失败！原因：" + ex.Message }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #region 获取分站
        /// <summary>
        /// 获取分站
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetStation()
        {
            try
            {
                string version = Request.Form["version"].ToString();//20151109版本标识
                string state = Request.Form["biaozhi"].ToString();//20151109修改标识(如果为0说明是更新，为1是全部下载)
                MobileTaskBLL bll = new MobileTaskBLL();
                var result = new object();
                //增加缓存
                //lock (m_SyncRoot)
                //{
                //    result = CacheHelper.GetCache("GetStation");
                //    if (result == null)
                //    {
                result = bll.GetMainDictionary("TStation", version, state);
                //CacheHelper.SetCache("GetStation", result);
                //    }
                //}
                return Json(result);
            }
            catch (Exception e)
            {
                return this.Json("-1");
            }
        }
        #endregion

        #region 获取医院列表信息
        /// <summary>
        /// 获取医院列表信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetHospitalInfo()
        {
            try
            {
                string version = Request.Form["version"].ToString();//20151109版本标识
                string state = Request.Form["biaozhi"].ToString();//20151109修改标识
                MobileTaskBLL bll = new MobileTaskBLL();
                var result = new object();
                //增加缓存
                //lock (m_SyncRoot)
                //{
                //result = CacheHelper.GetCache("GetHospitalInfo");
                //if (result == null)
                //{
                result = bll.GetMainDictionary("THospitalInfo", version, state);
                //CacheHelper.SetCache("GetHospitalInfo", result);
                //    }
                //}
                return Json(result);
            }
            catch (Exception e)
            {
                return this.Json("-1");
            }
        }
        #endregion

        #region 获取车辆列表信息
        /// <summary>
        /// 获取车辆列表信息
        /// 20151109
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetAmbulance()
        {
            try
            {
                string version = Request.Form["version"].ToString();//20151109版本标识
                string state = Request.Form["biaozhi"].ToString();//20151109修改标识
                MobileTaskBLL bll = new MobileTaskBLL();
                var result = new object();
                result = bll.GetMainDictionary("TAmbulance", version, state);
                return Json(result);
            }
            catch (Exception e)
            {
                return this.Json("-1");
            }
        }
        #endregion

        #region 获取药品、耗材、措施列表信息
        /// <summary>
        /// 获取药品、耗材、措施列表信息
        /// 20151110
        /// 20211018 plq 医保上线移植，增加医保物资获取
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetMaterial()
        {
            try
            {
                string version = Request.Form["version"].ToString();//20151110版本标识
                string state = Request.Form["biaozhi"].ToString();//20151110修改标识
                string workcode = Request.Form["workcode"].ToString();//当前登录人工号  20211018 
            
                MobileTaskBLL bll = new MobileTaskBLL();
                List<I_Material> list = new List<I_Material>();
                list = bll.GetMainDictionary("I_Material", version, state);
                List<I_Material> yblist = new List<I_Material>(); //add2021-10-18 plq
                yblist = GetYBMaterial(workcode);
                yblist = yblist.Concat(list).ToList();
                return Json(yblist);
            }
            catch (Exception e)
            {
                return this.Json("-1");
            }
        }
        #endregion

        #region 获取病历字典列表信息
        /// <summary>
        /// 获取病历字典列表信息
        /// 20151110
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetMDictionary()
        {
            try
            {
                string version = Request.Form["version"].ToString();//20151110版本标识
                string state = Request.Form["biaozhi"].ToString();//20151110修改标识
                MobileTaskBLL bll = new MobileTaskBLL();
                var result = new object();
                result = bll.GetMainDictionary("M_Dictionary", version, state);
                return Json(result);
            }
            catch (Exception e)
            {
                return this.Json("-1");
            }
        }
        #endregion

        #region 获取病历字典类型列表信息
        /// <summary>
        /// 获取病历字典类型列表信息
        /// 20151110
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetMDictionaryType()
        {
            try
            {
                string version = Request.Form["version"].ToString();//20151110版本标识
                string state = Request.Form["biaozhi"].ToString();//20151110修改标识
                MobileTaskBLL bll = new MobileTaskBLL();
                var result = new object();
                result = bll.GetMainDictionary("M_DictionaryType", version, state);
                return Json(result);
            }
            catch (Exception e)
            {
                return this.Json("-1");
            }
        }
        #endregion

        #region 获取病历"病种分类字典表"列表信息
        /// <summary>
        /// 获取病历"病种分类字典表"列表信息
        /// 20151127
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetMZCaseTemplate()
        {
            try
            {
                string version = Request.Form["version"].ToString();//20151110版本标识
                string state = Request.Form["biaozhi"].ToString();//20151110修改标识
                MobileTaskBLL bll = new MobileTaskBLL();
                var result = new object();
                result = bll.GetMainDictionary("M_ZCaseTemplate", version, state);
                return Json(result);
            }
            catch (Exception e)
            {
                return this.Json("-1");
            }
        }
        #endregion

        #region 获取病历"心电图印象字典表"列表信息
        /// <summary>
        /// 获取病历"心电图印象字典表"列表信息
        /// 20151127
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetMZECGImpression()
        {
            try
            {
                string version = Request.Form["version"].ToString();//20151110版本标识
                string state = Request.Form["biaozhi"].ToString();//20151110修改标识
                MobileTaskBLL bll = new MobileTaskBLL();
                var result = new object();
                result = bll.GetMainDictionary("M_ZECGImpression", version, state);
                return Json(result);
            }
            catch (Exception e)
            {
                return this.Json("-1");
            }
        }
        #endregion

        #region 获取病历"初步印象字典表"列表信息
        /// <summary>
        /// 获取病历"初步印象字典表"列表信息
        /// 20151127
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetMZICDNew()
        {
            try
            {
                string version = Request.Form["version"].ToString();//20151110版本标识
                string state = Request.Form["biaozhi"].ToString();//20151110修改标识
                MobileTaskBLL bll = new MobileTaskBLL();
                var result = new object();
                result = bll.GetMainDictionary("M_ZICDNew", version, state);
                return Json(result);
            }
            catch (Exception e)
            {
                return this.Json("-1");
            }
        }
        #endregion

        #region 获取病历"症状待查字典表"列表信息
        /// <summary>
        /// 获取病历"症状待查字典表"列表信息
        /// 20151127
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetMZSymptomPendingInvestigation()
        {
            try
            {
                string version = Request.Form["version"].ToString();//20151110版本标识
                string state = Request.Form["biaozhi"].ToString();//20151110修改标识
                MobileTaskBLL bll = new MobileTaskBLL();
                var result = new object();
                result = bll.GetMainDictionary("M_ZSymptomPendingInvestigation", version, state);
                return Json(result);
            }
            catch (Exception e)
            {
                return this.Json("-1");
            }
        }
        #endregion

        #region 2016-12-13 zch 添加 根据任务编码和病历序号查询病历 一对多关系
        /// <summary>
        /// 根据任务编码和病历序号查询病历
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetPatientRecordList()
        {
            string TaskCode = Request.Form["TaskCode"].ToString();
            // int PatientOrder = Convert.ToInt32(Request.Form["PatientOrder"]);
            int PatientOrder = new MobilePatientRecordBLL().GetPatientOrderByTaskCode(TaskCode);
            List<MobilePRListInfo> allPRList = new List<MobilePRListInfo>();

            for (int i = 1; i <= PatientOrder; i++)
            {
                M_PatientRecord pr = null;
                M_PatientRecordAppend pra = null;
                M_PatientRecordCPR prc = null;

                List<M_PatientRecordRescue> prrs = null;//救治记录
                List<M_PatientRecordMeasure> prms = null;//措施
                List<M_PatientRecordDrug> prds = null;//药品表
                List<M_PatientRecordSanitation> prss = null;//耗材表 
                int ChargeType = 0;
                ChargeType = new MobilePatientRecordBLL().GetIFChargeByTaskCode(TaskCode, i);

                //下面方法需要修改 2015-12-04
                new MobilePatientRecordBLL().GetPatientAndRescueInfo(TaskCode, i, out pr, out pra, out prc, out prrs, out prms, out prds, out prss);

                MobilePRListInfo mprList = new MobilePRListInfo();
                mprList.pr = pr;
                mprList.pra = pra;
                mprList.prc = prc;
                mprList.prrs = prrs;
                mprList.prms = prms;
                mprList.prds = prds;
                mprList.prss = prss;
                mprList.prds = prds;
                mprList.ChargeType = ChargeType;

                // string atemp = JsonHelper.Obj2JsonStr(new { pr, pra, prc, prrs, prms, prds, prss, ChargeType });
                allPRList.Add(mprList);
            }
            if (allPRList.Count > 0)
            {
                return Json(new { success = true, list = allPRList }, "appliction/json", JsonRequestBehavior.AllowGet);

            }
            else
            {
                int ChargeType = 0;
                M_PatientRecord pr = null;
                M_PatientRecordAppend pra = null;
                M_PatientRecordCPR prc = null;

                List<M_PatientRecordRescue> prrs = null;//救治记录
                List<M_PatientRecordMeasure> prms = null;//措施表
                List<M_PatientRecordDrug> prds = null;//药品表
                List<M_PatientRecordSanitation> prss = null;//耗材表 
                M_AttemperData result = new M_PatientRecordBLL().GetAttemperData(TaskCode, "");//根据任务编码获取调度信息
                pr = new M_PatientRecord();
                pr.CallOrder = result.CallOrder;
                pr.PatientOrder = 1;
                pr.LocalAddress = result.LocalAddress;
                pr.Name = result.Name;
                pr.Sex = result.Sex;
                pr.Age = result.Age;
                pr.AgeType = result.AgeType;
                pr.Station = result.Station;
                pr.OutStationCode = result.StationCode;
                pr.DrivingTime = result.DrivingTime;//出车时间
                pr.ArriveSceneTime = result.ArriveSceneTime;//到达现场时刻
                pr.LeaveSceneTime = result.LeaveSceneTime;//离开现场时刻
                pr.ArriveDestinationTime = result.ArriveDestinationTime;//到达医院时刻
                pr.SendAddress = result.SendAddress;
                pr.Driver = result.Driver;
                pr.DoctorAndNurse = result.Doctor + result.Nurse;
                pr.StretcherBearersI = result.StretcherBearers;
                pr.ContactTelephone = result.ContactTelephone;
                pr.ForHelpTelephone = result.ForHelpPhone;//20151211呼救电话
                pr.ForArea = result.Area;//20151211区域
                pr.OriginalTaskType = result.AlarmType;//20151211原事件类型
                return Json(new { success = true, pr = pr, pra = pra, prc = prc, prrs = prrs, prms = prms, prds = prds, prss = prss, ChargeType }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }
        #endregion


        //2018-05-04 zch
        [HttpPost]
        public ActionResult GetChargeDictionary()
        {
            try
            {
                M_PatientChargeBLL bll = new M_PatientChargeBLL();
                var result = new object();
                result = bll.GetChargeDictionary();
                return Json(result);
            }
            catch (Exception e)
            {
                return this.Json("");
            }
        }

        #region PAD上传图片 add2024-08-12 plq

        //2020-07-27 sr MobileTask/SubmitPatientImg
        [HttpPost]
        public ActionResult SubmitPatientImg()
        {
            try
            {
                int ret = 0;
                string TaskCode = Request.Form["TaskCode"].ToString();
                int PatientOrder = Convert.ToInt32(Request.Form["PatientOrder"]);
                int TypeCode = Convert.ToInt32(Request.Form["TypeCode"]);
                string imgStr = Request.Form["ImgList"].ToString();
                List<M_PatientRecordIMG> prrs = JsonHelper.GetJsonInfoBy<List<M_PatientRecordIMG>>(imgStr);
                string fileroot = AppConfig.GetConfigString("LogPath");
                if (prrs.Count > 0)
                {
                    new MobileTaskBLL().DeleteTaskImg(TaskCode, TypeCode, PatientOrder);
                    int i = 0;
                    string pathImg = fileroot + "Images\\APPUpload\\" + DateTime.Now.ToString("yyyyMM") + "\\" + TaskCode + "\\" + PatientOrder.ToString() + "\\" + TypeCode.ToString();
                    if (Directory.Exists(pathImg))
                    {
                        Directory.Delete(pathImg, true);
                    }
                    foreach (M_PatientRecordIMG img in prrs)
                    {
                        i++;
                        img.SubmitTime = DateTime.Now;
                        //将base64转换为图片并且存储到服务器上 
                        //将图片地址存储到数据库中
                        string pathStr = fileroot + "Images\\APPUpload\\" + DateTime.Now.ToString("yyyyMM") + "\\" + img.TaskCode + "\\" + img.PatientOrder.ToString() + "\\" + img.TypeCode.ToString() + "\\" + img.PatientOrder.ToString() + "-" + img.TypeCode.ToString() + "-" + i.ToString() + ".jpg";
                        Base64.Base64StrToImage(img.Img, pathStr);//20210527注释
                        img.ImgPath = pathStr;
                        img.ID = System.Guid.NewGuid();
                        img.Img = "";
                        //img.PatientOrder = PatientOrder;
                        ret += new M_PatientRecordIMGBLL().Add(img);
                    }
                }
                else
                {
                    ret = 1;
                    new MobileTaskBLL().DeleteTaskImg(TaskCode, TypeCode, PatientOrder);
                    string pathStr = fileroot + "Images\\APPUpload\\" + DateTime.Now.ToString("yyyyMM") + "\\" + TaskCode + "\\" + PatientOrder.ToString() + "\\" + TypeCode.ToString();
                    if (Directory.Exists(pathStr))
                    {
                        Directory.Delete(pathStr, true);
                    }
                }
                if (ret < 1 && prrs.Count > 0)
                    return Json(new { success = false, msg = "上传图片失败！" }, "appliction/json", JsonRequestBehavior.AllowGet);
                else
                    return Json(new { success = true, msg = "上传图片成功!" }, "appliction/json", JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                LogUtility.Error("BM/MobileTask/SubmitPatientImg", "上传图片失败！" + ex.Message);
                return Json(new { success = false, msg = "上传图片失败！" + ex.Message }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }

        //2020-04-10 zch  MobileTask/GetPatientImg
        [HttpPost]
        public ActionResult GetPatientImg()
        {
            string TaskCode = Request.Form["TaskCode"].ToString();
            int PatientOrder = Convert.ToInt32(Request.Form["PatientOrder"]);
            int TypeCode = Convert.ToInt32(Request.Form["TypeCode"]);
            List<M_PatientRecordIMG> imgList = new List<M_PatientRecordIMG>();

            if (TypeCode == -1)
                imgList = new M_PatientRecordIMGBLL().GetListBy(p => p.TaskCode == TaskCode && p.PatientOrder == PatientOrder).OrderBy(p => p.TypeCode).ThenBy(p => p.SubmitTime).ToList();
            else
                imgList = new M_PatientRecordIMGBLL().GetListBy(p => p.TaskCode == TaskCode && p.PatientOrder == PatientOrder && p.TypeCode == TypeCode).OrderBy(p => p.SubmitTime).ToList();

            if (imgList != null)
            {
                foreach (M_PatientRecordIMG img in imgList)
                {
                    string pathStr = img.ImgPath;
                    img.Img = Base64.ImageToBase64(pathStr);//20210527注释
                    img.ImgPath = "";
                }
                return new JsonResult()
                {
                    Data = new { success = true, ImgList = imgList },
                    MaxJsonLength = int.MaxValue,
                    ContentType = "application/json"
                };
                //return Json(new { success = true, ImgList = imgList }, "appliction/json", JsonRequestBehavior.AllowGet);
            }

            return new JsonResult()
            {
                Data = new { success = false, ImgList = "" },
                MaxJsonLength = int.MaxValue,
                ContentType = "application/json"
            };
            // return Json(new { success = false, ImgList = "" }, "appliction/json", JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 医保上线移植 add2021-10-18 plq

        #region 2021-08-31 SR  医保上传病历调用接口 //2021-10-18 plq医保上线移植
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Boolean SavePatientRecordMaterialUse(List<M_PatientRecordDrug> prds, List<M_PatientRecordSanitation> prss, List<M_PatientRecordMeasure> prms, string TaskCode, int PatientOrder)
        {
            List<M_PatientRecordMaterialUse> prmu = new List<M_PatientRecordMaterialUse>();
            string strURL = "";
            string responseText = "";
            string PRecordMaterials = "";
            try
            {
                //药品
                if (prds != null)
                {
                    foreach (M_PatientRecordDrug info in prds)
                    {
                        List<I_Material> imList = new I_MaterialBLL().GetListBy(p => p.ID == info.DrugCode && p.YBCode != null && p.YBCode.Length > 0).ToList();
                        if (imList != null)
                        {
                            M_PatientRecordMaterialUse mprmu = new M_PatientRecordMaterialUse();
                            mprmu.TaskCode = info.TaskCode;
                            mprmu.PatientOrder = info.PatientOrder;
                            mprmu.PRType = 1;
                            mprmu.MaterialCode = info.DrugCode;
                            mprmu.Dosage = Convert.ToDouble(info.Dosage);
                            mprmu.SelectOrder = info.SelectOrder;
                            mprmu.Remark = info.Remark;
                            prmu.Add(mprmu);
                        }
                    }
                }
                //耗材
                if (prss != null)
                {
                    foreach (M_PatientRecordSanitation info in prss)
                    {
                        List<I_Material> imList = new I_MaterialBLL().GetListBy(p => p.ID == info.SanitationCode && p.YBCode != null && p.YBCode.Length > 0).ToList();
                        if (imList != null)
                        {
                            M_PatientRecordMaterialUse mprmu = new M_PatientRecordMaterialUse();
                            mprmu.TaskCode = info.TaskCode;
                            mprmu.PatientOrder = info.PatientOrder;
                            mprmu.PRType = 2;
                            mprmu.MaterialCode = info.SanitationCode;
                            mprmu.Dosage = Convert.ToDouble(info.NumberOfTimes);
                            mprmu.SelectOrder = info.SelectOrder;
                            mprmu.Remark = info.Remark;
                            prmu.Add(mprmu);
                        }
                    }
                }
                //救治措施
                if (prms != null)
                {
                    foreach (M_PatientRecordMeasure info in prms)
                    {
                        M_PatientRecordMaterialUse mprmu = new M_PatientRecordMaterialUse();
                        mprmu.TaskCode = info.TaskCode;
                        mprmu.PatientOrder = info.PatientOrder;
                        mprmu.PRType = 3;
                        mprmu.MaterialCode = info.RescueMeasureCode;
                        mprmu.Dosage = Convert.ToDouble(info.NumberOfTimes);
                        mprmu.SelectOrder = info.SelectOrder;
                        mprmu.Remark = info.Remark;
                        prmu.Add(mprmu);
                    }
                }
                if (prmu != null)
                {
                    if (prmu.Count > 0)
                    {
                        strURL = ConfigurationManager.AppSettings["YBWebUrlSaveUse"].ToString();
                        PRecordMaterials = JsonHelper.Obj2JsonStr(prmu); ;
                        System.Net.HttpWebRequest request;
                        request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                        //Post请求方式
                        request.Method = "POST";
                        // 内容类型
                        request.ContentType = "application/x-www-form-urlencoded";
                        // 参数经过URL编码
                        StringBuilder sb = new StringBuilder();
                        sb.Append("&PRecordMaterials=" + PRecordMaterials);
                        byte[] payload;
                        //将URL编码后的字符串转化为字节
                        payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                        //设置请求的 ContentLength 
                        request.ContentLength = payload.Length;
                        //获得请求流
                        System.IO.Stream writer = request.GetRequestStream();
                        //将请求参数写入流
                        writer.Write(payload, 0, payload.Length);
                        // 关闭请求流
                        writer.Close();
                        System.Net.HttpWebResponse response;
                        // 获得响应流
                        response = (System.Net.HttpWebResponse)request.GetResponse();
                        System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        responseText = myreader.ReadToEnd();
                        myreader.Close();
                        //解析返回的实体
                        ResultInfo rinfo = js.Deserialize<ResultInfo>(responseText);
                        if (rinfo.status == "0")
                        {
                            return true;
                        }
                        else
                        {
                            LogUtility.Error("MobileTaskController/SavePatientRecordMaterialUse", "医保SaveUse方法失败：" + rinfo.msg);
                            return false;
                        }
                    }
                    else
                    {
                        strURL = ConfigurationManager.AppSettings["YBWebUrlDeleteUse"].ToString();
                        PRecordMaterials = JsonHelper.Obj2JsonStr(prmu); ;
                        System.Net.HttpWebRequest request;
                        request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                        //Post请求方式
                        request.Method = "POST";
                        // 内容类型
                        request.ContentType = "application/x-www-form-urlencoded";
                        // 参数经过URL编码
                        StringBuilder sb = new StringBuilder();
                        sb.Append("&TaskCode=" + TaskCode);
                        sb.Append("&PatientOrder=" + PatientOrder);
                        byte[] payload;
                        //将URL编码后的字符串转化为字节
                        payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                        //设置请求的 ContentLength 
                        request.ContentLength = payload.Length;
                        //获得请求流
                        System.IO.Stream writer = request.GetRequestStream();
                        //将请求参数写入流
                        writer.Write(payload, 0, payload.Length);
                        // 关闭请求流
                        writer.Close();
                        System.Net.HttpWebResponse response;
                        // 获得响应流
                        response = (System.Net.HttpWebResponse)request.GetResponse();
                        System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        responseText = myreader.ReadToEnd();
                        myreader.Close();
                        //解析返回的实体
                        ResultInfo rinfo = js.Deserialize<ResultInfo>(responseText);
                        if (rinfo.status == "0")
                        {
                            return true;
                        }
                        else
                        {
                            LogUtility.Error("MobileTaskController/SavePatientRecordMaterialUse", "医保DeleteUse方法失败：" + rinfo.msg);
                            return false;
                        }
                    }

                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("MobileTaskController/SavePatientRecordMaterialUse", "程序异常：" + ex.Message);
                return false;
            }
        }
        #endregion

        #region 20210901 se 医保获取物资接口 //2021-10-18 plq医保上线移植
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public List<I_Material> GetYBMaterial(string WorkCode)
        {
            try
            {
                string strURL = "";
                string responseText = "";
                strURL = ConfigurationManager.AppSettings["YBWebUrlGetYBMaterial"].ToString();
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                //Post请求方式
                request.Method = "POST";
                // 内容类型
                request.ContentType = "application/x-www-form-urlencoded";
                // 参数经过URL编码
                StringBuilder sb = new StringBuilder();
                sb.Append("&WorkCode=" + WorkCode);
                byte[] payload;
                //将URL编码后的字符串转化为字节
                payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                //设置请求的 ContentLength 
                request.ContentLength = payload.Length;
                //获得请求流
                System.IO.Stream writer = request.GetRequestStream();
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                // 关闭请求流
                writer.Close();
                System.Net.HttpWebResponse response;
                // 获得响应流
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseText = myreader.ReadToEnd();
                myreader.Close();
                //解析返回的实体
                if (responseText != "\"-1\"")
                {
                    List<I_Material> rinfo = JsonHelper.GetJsonInfoBy<List<I_Material>>(responseText);//解析物资信息实体
                    return rinfo;
                }
                else
                {
                    LogUtility.Error("MobileTaskController/GetYBMaterial", "获取医保物资失败：" + responseText);
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("MobileTaskController/GetYBMaterial", "程序异常：" + ex.Message);
                return null;
            }
        }
        #endregion

        #region PAD 端上传日志接口 20210914 sr //2021-10-18 plq医保上线移植
        //20211025 zll 如果有错误，pad端可上传日志，进行查询
        [HttpPost]
        public ActionResult SaveLog(HttpPostedFileBase LogFile)
        {
            try
            {
                string path = AppConfig.GetConfigString("LogPath");//获得webconfig中的路径
                if (LogFile != null)
                {
                    string fileName = System.IO.Path.GetFileName(LogFile.FileName);
                    var now = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();
                    string fileExtention = Path.GetExtension(LogFile.FileName);
                    var filePath = path + "PadLog/" + now;
                    if (!Directory.Exists(filePath))//创建时否存在目录。不存在则进行创建
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    if (System.IO.File.Exists(fileName))  //1、首先判断文件是否存在
                    {
                        System.IO.File.Delete(fileName);
                    }
                    if (fileExtention != null)
                    {
                        fileExtention = fileExtention.ToLower();
                        if ("(.txt)|(.zip)|(.rar)".Contains(fileExtention))
                        {
                            LogFile.SaveAs(Path.Combine(filePath, fileName));
                            filePath = filePath + "/" + fileName;
                            return Json(new { result = "OK", message = "保存成功!" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
                        }
                        else
                        {
                            JsonResult j = this.Json(new { result = "Error", message = "格式不正确，请上传(.txt)|(.zip)|(.rar)类型的文件!" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
                            return j;
                        }
                    }
                }
                LogUtility.Error("MobileTaskController/SaveLog", "保存失败!");
                return Json(new { result = "Error", message = "保存失败!" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                LogUtility.Error("MobileTaskController/SaveLog", ex.Message);
                return Json(new { result = "Error", message = ex.Message }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
            }

        }
        #endregion


        #endregion

        #region 移动支付 add2022-01-13 plq 移植闵行代码

        #region 2020-08-13 SR  请求网络支付（）二维码地址
        /// <summary>
        /// 请求网络支付(支付宝：1，微信：2)二维码地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetQRCodeUrl()
        {
            PayInfo pinfo = new PayInfo();
            pinfo.result = false;
            pinfo.obj = "生成订单失败";
            string strURL = "";
            string task_code = Request.Form["task_code"].ToString();//任务编码
            int patient_order = int.Parse(Request.Form["patient_order"]);//病历序号
            string work_code = Request.Form["work_code"].ToString();//工号
            string total_amount = Request.Form["total_amount"].ToString();//金额 以分为单位       
            string sign = Request.Form["sign"].ToString();//协议：pad端加密后传过来和服务端加密后的值要相同  
            string str = "task_code=" + task_code + "&patient_order=" + patient_order + "&total_amount=" + total_amount + "&work_code=" + work_code + "";
            //然后BASE64加密
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            string base64 = Convert.ToBase64String(bytes);
            //再MD5加密
            string serversign = getMd5Hash(str);
            string no = DateTime.Now.ToString("yyyyMMddHHmmss") + work_code;//订单号:时间拼上工号 
            string responseText = "";
            double money = double.Parse(total_amount) / 100;
            if (serversign == sign)//PAD端的sign和服务端的serversign要一致才算通过验证
            {
                try
                {
                    //将订单号相关信息插库
                    new MobileTaskBLL().Insert(no, task_code, patient_order, work_code, "", money, DateTime.Now, "", false, 0, "", "", "", "", -1);
                    strURL = YinLianUrl + "/GetQRCode";
                    System.Net.HttpWebRequest request;
                    request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                    //Post请求方式
                    request.Method = "POST";
                    // 内容类型
                    request.ContentType = "application/x-www-form-urlencoded";
                    // 参数经过URL编码
                    StringBuilder sb = new StringBuilder();
                    sb.Append("&out_trade_no=" + no);
                    sb.Append("&total_fee=" + total_amount);
                    byte[] payload;
                    //将URL编码后的字符串转化为字节
                    payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                    //设置请求的 ContentLength 
                    request.ContentLength = payload.Length;
                    //获得请 求流
                    System.IO.Stream writer = request.GetRequestStream();
                    //将请求参数写入流
                    writer.Write(payload, 0, payload.Length);
                    // 关闭请求流
                    writer.Close();
                    System.Net.HttpWebResponse response;
                    // 获得响应流
                    response = (System.Net.HttpWebResponse)request.GetResponse();
                    System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseText = myreader.ReadToEnd();
                    myreader.Close();
                    //解析支付宝、微信服务程序返回的实体
                    //JsonResultInfo jresult = js.Deserialize<JsonResultInfo>(responseText);
                    ResultInfo rinfo = js.Deserialize<ResultInfo>(responseText);
                    if (rinfo.result_code == "0")//rinfo.obj != null && rinfo.code == 200)
                    {
                        pinfo.result = true;
                        pinfo.outtradeno = no;
                        pinfo.obj = rinfo.code_url.ToString();
                        LogUtility.Debug("MobileTaskController/GetQRCodeUrl", "请求生成二维码成功");
                    }
                }
                catch (Exception ex)
                {
                    LogUtility.Error("MobileTaskController/GetQRCodeUrl", "程序异常：" + ex.Message);
                }
            }
            return Json(pinfo);
        }

        //MD5加密
        public string getMd5Hash(string input)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

        #endregion

        #region 请求网络支付(支付宝：1，微信：2)支付结果
        /// <summary>
        /// 请求网络支付(支付宝：1，微信：2)支付结果
        /// 20200814
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetNetWorkPayResult()
        {
            PayInfo pinfo = new PayInfo();
            pinfo.result = false;
            pinfo.obj = "错误";
            string strURL = "";
            try
            {
                string outtradeno = Request.Form["outtradeno"].ToString();
                //int paytype = int.Parse(Request.Form["paytype"]);//支付类型 
                //string trade_state = Request.Form["trade_state"].ToString();
                string responseText = "";
                strURL = YinLianUrl + "/QueryOrder";
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                //Post请求方式
                request.Method = "POST";
                // 内容类型
                request.ContentType = "application/x-www-form-urlencoded";
                // 参数经过URL编码
                StringBuilder sb = new StringBuilder();
                sb.Append("&out_trade_no=" + outtradeno);
                byte[] payload;
                //将URL编码后的字符串转化为字节
                payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                //设置请求的 ContentLength 
                request.ContentLength = payload.Length;
                //获得请 求流
                System.IO.Stream writer = request.GetRequestStream();
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                // 关闭请求流
                writer.Close();
                System.Net.HttpWebResponse response;
                // 获得响应流
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseText = myreader.ReadToEnd();
                myreader.Close();
                //解析支付宝、微信服务程序返回的实体
                //JsonResultInfo jresult = js.Deserialize<JsonResultInfo>(responseText);
                ResultInfo rinfo = js.Deserialize<ResultInfo>(responseText);
                string paytype = "";
                if (rinfo.trade_state == "SUCCESS")//已经支付
                {
                    pinfo.result = true;
                    pinfo.outtradeno = outtradeno;
                    pinfo.obj = "支付成功";
                    //根据订单号和返回的支付结果 更新表中相应字段
                    paytype = rinfo.trade_type; //交易类型
                    string endtime = DateTime.Now.ToString();
                    new MobileTaskBLL().Update(outtradeno, 1, endtime, paytype);
                    LogUtility.Debug("MobileTaskController/GetNetWorkPayResult", "订单号:" + outtradeno + "支付成功");
                }
                else if (rinfo.trade_state == "CLOSED")
                {
                    pinfo.result = false;
                    pinfo.outtradeno = outtradeno;
                    pinfo.obj = "订单已关闭";
                    //根据订单号和返回的支付结果 更新表中相应字段                                          
                    string endtime = DateTime.Now.ToString();
                    new MobileTaskBLL().Update(outtradeno, 2, endtime, paytype);
                    LogUtility.Debug("MobileTaskController/GetNetWorkPayResult", "订单号:" + outtradeno + "超时关闭");
                }
                else if (rinfo.trade_state == "REFUND")
                {
                    pinfo.result = false;
                    pinfo.outtradeno = outtradeno;
                    pinfo.obj = "已申请退款";
                    //根据订单号和返回的支付结果 更新表中相应字段    
                    //string endtime = DateTime.Now.ToString();
                    //new MobileTaskBLL().Update(outtradeno, 1, endtime, paytype);
                    //LogUtility.Debug("MobileTaskController/GetNetWorkPayResult", "订单号:" + outtradeno + "超时关闭");
                }
                else if (rinfo.trade_state == "PAYERROR")
                {
                    //订单错误
                    pinfo.result = false;
                    pinfo.outtradeno = outtradeno;
                    pinfo.obj = "支付失败";
                    //根据订单号和返回的支付结果 更新表中相应字段         
                    string endtime = DateTime.Now.ToString();
                    new MobileTaskBLL().Update(outtradeno, 2, endtime, paytype);
                    LogUtility.Debug("MobileTaskController/GetNetWorkPayResult", "订单号:" + outtradeno + "支付失败");
                }
                else if (rinfo.trade_state == "NOTPAY")
                {
                    pinfo.result = false;
                    pinfo.outtradeno = outtradeno;
                    pinfo.obj = "等待支付";
                    //根据订单号和返回的支付结果 更新表中相应字段        
                    string endtime = DateTime.Now.ToString();
                    new MobileTaskBLL().Update(outtradeno, 2, endtime, paytype);
                    LogUtility.Debug("MobileTaskController/GetNetWorkPayResult", "订单号:" + outtradeno + "等待支付");
                }
                else
                {
                    pinfo.result = false;
                    pinfo.outtradeno = outtradeno;
                    pinfo.obj = "交易失败";
                    //根据订单号和返回的支付结果 更新表中相应字段         
                    string endtime = DateTime.Now.ToString();
                    new MobileTaskBLL().Update(outtradeno, 2, endtime, paytype);
                    LogUtility.Debug("MobileTaskController/GetNetWorkPayResult", "订单号:" + outtradeno + "交易失败");
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("MobileTaskController/GetNetWorkPayResult", "程序异常：" + ex.Message);
            }
            return Json(pinfo);
        }
        #endregion

        #region 请求网络支付(支付宝：1，微信：2)申请退款
        /// <summary>
        /// 请求网络支付(支付宝：1，微信：2)申请退款
        /// 20171206
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetNetWorkCancel()
        {
            PayInfo pinfo = new PayInfo();
            pinfo.result = false;
            pinfo.obj = "错误";
            try
            {
                string strURL = "";
                string outtradeno = Request.Form["outtradeno"].ToString();
                string total_amount = Request.Form["total_amount"].ToString();
                //string task_code = Request.Form["task_code"].ToString();//任务编码
                //int patient_order = int.Parse(Request.Form["patient_order"]);//病历序号
                string work_code = Request.Form["workcode"].ToString();
                string outrefundno = DateTime.Now.ToString("yyyyMMddHHmmss") + work_code;//订单号:时间拼上工号 
                string refundno = "";
                //查询是否已经进行银联退款
                if (!new MobileTaskBLL().ISRefund(outtradeno, ref refundno))
                {
                    string responseText = "";
                    strURL = YinLianUrl + "/RefundApply";
                    System.Net.HttpWebRequest request;
                    request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                    //Post请求方式
                    request.Method = "POST";
                    // 内容类型
                    request.ContentType = "application/x-www-form-urlencoded";
                    // 参数经过URL编码
                    StringBuilder sb = new StringBuilder();
                    sb.Append("&out_trade_no=" + outtradeno);
                    sb.Append("&out_refund_no=" + outrefundno);
                    sb.Append("&total_fee=" + total_amount);
                    sb.Append("&refund_fee=" + total_amount);
                    byte[] payload;
                    //将URL编码后的字符串转化为字节
                    payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                    //设置请求的 ContentLength 
                    request.ContentLength = payload.Length;
                    //获得请 求流
                    System.IO.Stream writer = request.GetRequestStream();
                    //将请求参数写入流
                    writer.Write(payload, 0, payload.Length);
                    // 关闭请求流
                    writer.Close();
                    System.Net.HttpWebResponse response;
                    // 获得响应流
                    response = (System.Net.HttpWebResponse)request.GetResponse();
                    System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseText = myreader.ReadToEnd();
                    myreader.Close();
                    //根据订单号和返回的撤销结果 更新表中相应字段
                    //JsonResultInfo jresult = js.Deserialize<JsonResultInfo>(responseText);
                    ResultInfo rinfo = js.Deserialize<ResultInfo>(responseText);
                    if (rinfo.result_code == "0")
                    {
                        pinfo.result = true;
                        pinfo.outtradeno = outrefundno;//换成退款单号
                        pinfo.obj = "申请退款成功";//rinfo.result;//
                        string endtime = DateTime.Now.ToString();
                        //new MobileTaskBLL().UpdateCancelResult(outtradeno,1, endtime);
                        new MobileTaskBLL().InsetCancelResult(outtradeno, outrefundno, work_code, endtime);
                        LogUtility.Debug("MobileTaskController/GetNetWorkPayResult", "订单号:" + outtradeno + "申请退款成功" + "，退款单号：" + outrefundno);
                    }
                    else
                    {
                        LogUtility.Debug("MobileTaskController/GetNetWorkPayResult", "订单号:" + outtradeno + "申请退款失败" + "，退款单号：" + outrefundno + responseText);
                    }
                }
                else
                {
                    pinfo.result = true;
                    pinfo.outtradeno = refundno;//换成退款单号
                    pinfo.obj = "申请退款成功";
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("MobileTaskController/GetNetWorkCancel", "程序异常：" + ex.Message);
            }
            return Json(pinfo);//撤销结果不返回给手机端，只返回空字符串
        }
        #endregion

        #region 查询订单状态
        /// <summary>
        /// 请求网络支付(支付宝：1，微信：2)支付结果
        /// 20211202
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetPayResult()
        {
            try
            {
                string strURL = "";
                string task_code = Request.Form["task_code"].ToString();//任务编码
                int patient_order = int.Parse(Request.Form["patient_order"]);//病历序号
                string outtradeno = "";
                new MobileTaskBLL().GetTradeNo(task_code, patient_order, out outtradeno);
                if (outtradeno.Length > 0)
                {
                    string responseText = "";
                    strURL = YinLianUrl + "/QueryOrder";
                    System.Net.HttpWebRequest request;
                    request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                    //Post请求方式
                    request.Method = "POST";
                    // 内容类型
                    request.ContentType = "application/x-www-form-urlencoded";
                    // 参数经过URL编码
                    StringBuilder sb = new StringBuilder();
                    sb.Append("&out_trade_no=" + outtradeno);
                    byte[] payload;
                    //将URL编码后的字符串转化为字节
                    payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                    //设置请求的 ContentLength 
                    request.ContentLength = payload.Length;
                    //获得请 求流
                    System.IO.Stream writer = request.GetRequestStream();
                    //将请求参数写入流
                    writer.Write(payload, 0, payload.Length);
                    // 关闭请求流
                    writer.Close();
                    System.Net.HttpWebResponse response;
                    // 获得响应流
                    response = (System.Net.HttpWebResponse)request.GetResponse();
                    System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseText = myreader.ReadToEnd();
                    myreader.Close();
                    //解析支付宝、微信服务程序返回的实体
                    ResultInfo rinfo = js.Deserialize<ResultInfo>(responseText);
                    string paytype = "";
                    paytype = rinfo.trade_type; //交易类型
                    if (rinfo.trade_state == "SUCCESS")//已经支付
                    {
                        //根据订单号和返回的支付结果 更新表中相应字段
                        string endtime = DateTime.Now.ToString();
                        new MobileTaskBLL().Update(outtradeno, 1, endtime, paytype);
                        LogUtility.Debug("MobileTaskController/GetPayResult", "订单号:" + outtradeno + "支付成功");
                        return Json(new { result = "SUCCESS", msg = outtradeno }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
                    }
                    else if (rinfo.trade_state == "CLOSED")
                    {
                        //根据订单号和返回的支付结果 更新表中相应字段        
                        string endtime = DateTime.Now.ToString();
                        new MobileTaskBLL().Update(outtradeno, 2, endtime, paytype);
                        LogUtility.Debug("MobileTaskController/GetPayResult", "订单号:" + outtradeno + "超时关闭");
                        return Json(new { result = "PAYERROR", msg = "未查到银联支付成功的记录！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
                    }
                    else if (rinfo.trade_state == "REFUND")
                    {
                        LogUtility.Debug("MobileTaskController/GetPayResult", "订单号:" + outtradeno + "转入退款");
                        return Json(new { result = "PAYERROR", msg = "未查到银联支付成功的记录！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
                    }
                    else if (rinfo.trade_state == "PAYERROR")
                    {
                        //根据订单号和返回的支付结果 更新表中相应字段         
                        string endtime = DateTime.Now.ToString();
                        new MobileTaskBLL().Update(outtradeno, 2, endtime, paytype);
                        LogUtility.Debug("MobileTaskController/GetPayResult", "订单号:" + outtradeno + "支付失败");
                        return Json(new { result = "PAYERROR", msg = "未查到银联支付成功的记录！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
                    }
                    else if (rinfo.trade_state == "NOTPAY")
                    {
                        //根据订单号和返回的支付结果 更新表中相应字段        
                        string endtime = DateTime.Now.ToString();
                        new MobileTaskBLL().Update(outtradeno, 2, endtime, paytype);
                        LogUtility.Debug("MobileTaskController/GetPayResult", "订单号:" + outtradeno + "等待支付");
                        return Json(new { result = "PAYERROR", msg = "未查到银联支付成功的记录！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        //根据订单号和返回的支付结果 更新表中相应字段         
                        string endtime = DateTime.Now.ToString();
                        new MobileTaskBLL().Update(outtradeno, 2, endtime, paytype);
                        LogUtility.Debug("MobileTaskController/GetPayResult", "订单号:" + outtradeno + "交易失败");
                        return Json(new { result = "PAYERROR", msg = "未查到银联支付成功的记录！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    return Json(new { result = "PAYERROR", msg = "未查到银联支付成功的记录！" }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("MobileTaskController/GetPayResult", "程序异常：" + ex.Message);
                return Json(new { result = "ERROR", msg = "程序异常：" + ex.Message }, "text/plain;charset=UTF-8", JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

        #endregion

        #region PAD端获取病历状态，是否已提交 add2023-10-17 plq

        /// <summary>
        /// 提供PAD端 获取病历状态，是否已提交
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult VerifyRecordState()
        {
            string task_code = Request.Form["task_code"].ToString();//任务编码
            int patient_order = int.Parse(Request.Form["patient_order"]);//病历序号

            M_PatientRecordBLL bll = new M_PatientRecordBLL();
            bool res = bll.VerifyRecordState(task_code, patient_order);
            if (res)
            {
                return Json(new { isSubmit = true, msg = "已提交" }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { isSubmit = false, msg = "未提交" }, "appliction/json", JsonRequestBehavior.AllowGet);
        }

        #endregion

    }
}
